<template>
  <div class="container">
    <el-form
      :inline="true"
      :model="params"
      label-width="70px"
      label-position="left"
      size="mini"
      class="demo-form-inline"
      style="padding-top: 18px;"
      @submit.native.prevent
    >
      <el-form-item label="申请人">
        <el-input clearable v-model="params.applyName" placeholder="申请人" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="批次ID">
        <el-input clearable v-model="params.id" placeholder="批次ID" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="批次名称">
        <el-input clearable v-model="params.batchName" placeholder="批次名称" class="the-input"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="params.state" placeholder="请选择">
          <el-option label="请选择" value></el-option>
          <el-option value="0" label="初始"></el-option>
          <el-option value="1" label="待运营审核"></el-option>
          <el-option value="2" label="待财务审核"></el-option>
          <el-option value="3" label="审核通过"></el-option>
          <el-option value="4" label="审核驳回"></el-option>
          <!-- <el-option value="5" label="已结束"></el-option> -->
          <el-option value="6" label="已作废"></el-option>
          <!-- <el-option value="7" label="发放中"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="发券主体">
        <el-select v-model="params.provider">
          <el-option label="请选择" value></el-option>
          <el-option label="平台" value="0"></el-option>
          <el-option label="商家" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button native-type="submit" type="primary" @click="doSearch">查询</el-button>
        <!-- <el-button type="primary" @click="toAddConfig">新增配置</el-button>
        <el-button type="primary" @click="batchReview">批量提审</el-button> -->
      </el-form-item>
    </el-form>
    <div class="button-field">
      <!-- <el-button type="primary" @click="doSearch" size="small">查询</el-button> -->
      <el-button type="primary" @click="toAddConfig" size="small">新增配置</el-button>
      <el-button type="primary" @click="batchReview" size="small">批量提审</el-button>
    </div>
    <el-table
      @select-all="onSelectAll"
      @select="onRowSelect"
      :data="tableData"
      style="width: 100%"
      border
      size="small"
      stripe
      :empty-text="emptyText"
      height="300"
    >
      <el-table-column fixed type="selection" width="55" align="center" :selectable="selectable"></el-table-column>
      <el-table-column prop="id" label="批次ID" width="180"></el-table-column>
      <el-table-column prop="batchName" label="批次名称" width="180"></el-table-column>
      <el-table-column prop="providedType" label="发放方式" width="180" :formatter="providedTypeFormat"></el-table-column>
      <el-table-column prop="provider" label="发券主体" width="180" :formatter="providerFormat"></el-table-column>
      <el-table-column prop="type" label="费用归属" width="180" :formatter="typeFormat"></el-table-column>
      <el-table-column prop="batchType" label="优惠券类型" width="180" :formatter="batchTypeFormat"></el-table-column>
      <el-table-column prop="batchMoney" label="优惠券金额/折扣" width="180" :formatter="batchMoneyFormat"></el-table-column>
      <el-table-column prop="limitMoney" label="优惠券限额" width="180"></el-table-column>
      <el-table-column prop="applicateNum" label="申请数量" width="180"></el-table-column>
      <el-table-column prop="stockNum" label="剩余数量" width="180"></el-table-column>
      <el-table-column prop="state" label="状态" width="180" :formatter="statusFormat"></el-table-column>
      <el-table-column prop="createTime" label="申请时间" width="180"></el-table-column>
      <el-table-column prop="applyName" label="申请人" width="180"></el-table-column>
      <el-table-column fixed="right" prop label="操作" width="280" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="toDetail(scope.row)">查看</el-button>
          <el-button type="text" size="small" v-if="scope.row.state !== 6 && scope.row.state !== 7" @click="toEdit(scope.row)">修改</el-button>
          <el-button type="text" size="small" v-if="scope.row.state === 0" @click="doExamine(scope.row)">提交审核</el-button>
          <el-button type="text" size="small" @click="doCopy(scope.row)">复制</el-button>
          <el-button type="text" size="small" v-if="scope.row.state !== 6" @click="doCancel(scope.row)">作废</el-button>
          <el-button type="text" size="small" @click="showLog(scope.row)">日志</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-area" style>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="params.pageSize"
        :current-page.sync="params.pageIndex"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        :page-count="pageCount"
      ></el-pagination>
    </div>
    <el-dialog title="优惠券日志" :visible.sync="dialogVisible" width="800">
      <el-table :data="logs" border size="small" stripe height="280">
        <el-table-column width="50" type="index" label="序号" align="center"></el-table-column>
        <el-table-column width="100" prop="createBy" label="操作人"></el-table-column>
        <el-table-column width="150" prop="operateDesc" label="操作类型"></el-table-column>
        <el-table-column prop="createTime" label="时间"></el-table-column>
        <el-table-column prop="remark" label="操作说明" width="100"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <coupon-dialog ref="couponDialog" @save="doSearch"/>
  </div>
</template>

<script>
import { getCouponList, batchAuditList, cancelCoupon, auditCoupons, copyCoupon, getLog } from '@/api/coupon'
import { getStatusNameByStatus, getOtherStatusNameByStatus } from '@/utils/status'
import { trim } from '@/utils'
import CouponDialog from './components/coupon-dialog';
export default {
  name: "couponList",
  components: {
    'coupon-dialog': CouponDialog
  },
  data() {
    return {
      // 用于显示或隐藏日志弹窗
      dialogVisible: false,
      params: {
        // 每页条数
        pageSize: 10,
        // 页码
        pageIndex: 1,
        // 申请人
        applyName: "广电测试",
        // 优惠券批次id
        id: "",
        // 优惠券批次名称
        batchName: "",
        // 状态
        state: "",
        // 发券主体
        provider: "",
      },
      emptyText: "",
      // 总条目数
      totalCount: 100,
      // 总页数
      pageCount: 0,
      ids: [],
      tableData: [],
      logs: []
    };
  },
  methods: {
    selectable (row, index) {
      return row.state !== 3 && row.state !== 1 && row.state !== 2;
    },
    // 监听选中事件
    onRowSelect(selection, row) {
      this.ids = selection.map((item) => item.id);
    },
    // 全选
    onSelectAll(selection) {
      this.ids = selection.map((item) => item.id);
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageIndex = 1;

      this.getCouponList();
    },
    handleCurrentChange(pageIndex) {
      this.params.pageIndex = pageIndex;
      this.getCouponList();
    },
    statusFormat(row, column, cellValue, index) {
      return getOtherStatusNameByStatus(cellValue);
    },
    batchMoneyFormat(row, column, cellValue, index) {
      if (row.batchDiscount) {
        return row.batchDiscount * 100 + "%";
      }
      return cellValue;
    },
    batchTypeFormat(row, column, cellValue, index) {
      return cellValue === 0 ? "现金券" : "满减券";
    },
    providedTypeFormat(row, column, cellValue, index) {
      return cellValue === 0 ? "定向发放" : "非定向发放";
    },
    providerFormat(row, column, cellValue, index) {
      return cellValue === 0 ? "平台" : "商家";
    },
    typeFormat(row, column, cellValue, index) {
      return cellValue === 0 ? "便捷青岛100%" : "商户100%";
    },
    toAddConfig() {
      // this.$router.push({
      //   path: "/addconfig",
      //   query: {
      //     viewType: "add",
      //   },
      // });
      this.$refs.couponDialog.add();
    },
    batchReview() {
      const ids = this.ids;
      if (ids.length === 0) {
        this.$message('请选择待审批的数据!');
        return;
      }

      this.$confirm("确定要对选中数据进行批量审核吗？", "审核确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        batchAuditList(ids).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
            this.refresh();
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error",
            });
          }
        });
      }).catch(e=>{
        console.log(e);
      });
    },
    doSearch() {
      this.params.pageIndex = 1;
      this.getCouponList();
    },
    getCouponList() {
      const loading = this.$loading({
        lock: true,
        text: "请稍等...",
      });
      // 加载优惠券列表
      getCouponList(this.params.pageIndex, this.params.pageSize, {
        applyName: trim(this.params.applyName),
        batchName: this.params.batchName.trim(),
        id: this.params.id,
        provider: this.params.provider,
        state: this.params.state,
      }).then((res) => {
        loading.close();
        // Todo
        // 如果成功返回 设置数据
        // 否则提示
        if (res.code === 200) {
          this.tableData = res.result.records;
          this.totalCount = res.result.total;
          this.pageCount = res.result.pages;
        } else {
          this.tableData = [];
          this.emptyText = res.msg;
          this.totalCount = 0;
          this.pageCount = 0;
        }
      });
    },
    showLog(row) {
      getLog(row.id).then(res=>{
        if (res.code === 200) {
          this.logs = res.result;
          this.dialogVisible = true;
          console.log(res);
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      })
      this.dialogVisible = true;
    },
    toEdit(item) {
      // this.$router.push({
      //   path: "/editconfig",
      //   query: {
      //     viewType: "edit",
      //     couponId: item.id,
      //     status: item.state
      //   },
      // });
      this.$refs.couponDialog.edit(item.id, item.state);
    },
    toDetail(item) {
      // this.$router.push({
      //   path: "/showconfig",
      //   query: {
      //     viewType: "detail",
      //     couponId: item.id
      //   },
      // });
      this.$refs.couponDialog.detail(item.id, item.state);
    },
    refresh() {
      this.pageIndex = 1;
      this.getCouponList();
    },
    doCancel(row) {
      this.$confirm("请确认是否作废当前优惠券批次？", "作废确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 确定
        cancelCoupon(row.id).then((res) => {
          if (res.code === 200) {
            this.$message({
              message: "作废成功",
              type: "success",
            });
            this.doSearch();
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error",
            });
          }
        });
      });
    },
    doCopy(row) {
      this.$confirm("请确认是否复制当前优惠券批次？", "复制确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        // this.$router.push({
        //   path: "/addconfig",
        //   query: {
        //     viewType: "copy",
        //     couponId: row.id
        //   },
        // });
        this.$refs.couponDialog.copy(row.id, row.state);
      });
    },
    // 提交审核
    doExamine(row) {
      auditCoupons(row.id).then(res=>{
        if (res.code === 200) {
          this.refresh();
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error",
          });
        }
      })
    },
  },
  mounted() {
    // 加载优惠券列表
    this.getCouponList();
  },
};
</script>

<style lang="scss">
</style>